import { constantRoutes } from "@/router";
import { getRouters } from "@/api/menu";
import Layout from "@/layout/index";

const permissions = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        console.log(constantRoutes, '领')
        const accessedRoutes = filterAsyncRouter([constantRoutes]);
        accessedRoutes.push({ path: "*", redirect: "/404", hidden: true });
        commit("SET_ROUTES", accessedRoutes);
        resolve(accessedRoutes);
        // getRouters().then(res => {
        //   const routes = res.data.filter(v => v.name && v.name === "System");
        //   console.log();
        //   const accessedRoutes = filterAsyncRouter([routes[0]]);
        //   accessedRoutes.push({ path: "*", redirect: "/404", hidden: true });
        //   commit("SET_ROUTES", accessedRoutes);
        //   resolve(accessedRoutes);
        // });
      });
    }
  }
};

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout;
        route.path = "/" + route.path;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    }
    return true;
  });
}
//  直接去子节点children遍历渲染
// eslint-disable-next-line no-unused-vars
function filterArray(asyncRouterMap) {
  const arr = [];
  asyncRouterMap.forEach((v) => {
    const route = {
      path: "/system",
      component: Layout,
      redirect: { name: v.name },
      name: v.name + "Index",
      meta: v.meta,
      children: [
        {
          path: v.path,
          component: loadView(v.component),
          name: v.name,
          meta: v.meta
        }
      ]
    };
    arr.push(route);
  });
  return arr;
}

export const loadView = view => {
  // 路由懒加载
  return () => import(`@/views/${view}`);
};

export default permissions;
